package com.chaodriod.common.system;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.swbyte.utils.system.AutoInstallService;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author SScience
 * @description 下载单个文件服务
 * @email chentushen.science@gmail.com
 * @data 2016/12/4
 */

public class DownLoadService extends Service {

    private static final String TAG = DownLoadService.class.getSimpleName();
    private static final String FILE_DIR = "update";
    private Context mContext;
    public DownloadManager mDownloadManager;
    private DownloadReceiver mDownloadReceiver;
    /**
     * 系统下载器分配的唯一下载任务id，可以通过这个id查询或者处理下载任务
     */
    public long mDownloadId = -1;
    public boolean mIsDownloading = false;
    private String apkPath;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public class MyBinder extends Binder {
        public DownLoadService getServices() {
            return DownLoadService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String url = intent.getStringExtra("url");
        if (url != null && !mIsDownloading) {
            mIsDownloading = true;
            Log.e(TAG, "开始下载");
            mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            startDownload(url);
            mDownloadReceiver = new DownloadReceiver();
            registerReceiver(mDownloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        }
        return START_NOT_STICKY;
    }

    /**
     * 开始下载apk
     *
     * @param apkUrl
     */
    public void startDownload(String apkUrl) {
        //开始下载
        String apkName = "new.apk";
        File file = new File(Environment.getExternalStoragePublicDirectory(FILE_DIR) + "/" + apkName);
        if (file.exists()) {
            file.delete();
        }
        // 设置下载地址
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));
        // 设置下载文件类型
        request.setMimeType("application/vnd.android.package-archive");
        // 设置下载到本地的文件夹和文件名
        request.setDestinationInExternalPublicDir(FILE_DIR, apkName);
        //在通知栏中显示，默认就是显示的
//        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        request.setTitle("YUNIK升级");
        /**
         * 如果我们希望下载的文件可以被系统的Downloads应用扫描到并管理，
         * 我们需要调用Request对象的setVisibleInDownloadsUi方法，传递参数true.
         */
        request.setDescription("Apk Downloading");
        request.setVisibleInDownloadsUi(false);
        // 执行下载，并返回任务唯一id
        mDownloadId = mDownloadManager.enqueue(request);
//        GlobalStatusModel.INSTANCE.setDownloadId(mDownloadId);
    }

    /**
     * 执行具体的静默安装逻辑，需要手机ROOT。
     */
    public class InstalTask extends AsyncTask<Boolean, Object, Boolean> {

        private String mPath;

        public InstalTask(String apkPath) {
            mPath = apkPath;
        }

        @Override
        protected Boolean doInBackground(Boolean... params) {
            boolean result = false;
            DataOutputStream dataOutputStream = null;
            BufferedReader errorStream = null;
            try {
                // 申请su权限
                Process process = Runtime.getRuntime().exec("su");
                dataOutputStream = new DataOutputStream(process.getOutputStream());
                // 执行pm install命令
                String command = "pm install -r " + mPath + "\n";
                dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
                dataOutputStream.flush();
                dataOutputStream.writeBytes("exit\n");
                dataOutputStream.flush();
                int i = process.waitFor();
                if (i == 0) {
                    result = true; // 正确获取root权限
                } else {
                    result = false; // 没有root权限，或者拒绝获取root权限
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
            } finally {
                try {
                    if (dataOutputStream != null) {
                        dataOutputStream.close();
                    }
                    if (errorStream != null) {
                        errorStream.close();
                    }
                } catch (IOException e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(Boolean hasRoot) {
            if (!hasRoot) {
                Log.e(TAG, "Root安装失败");
                installAuto(mPath);
            } else {
                Log.e(TAG, "Root安装成功");
            }
        }
    }

    /**
     * 自动安装
     *
     * @param apkPath
     */
    public void installAuto(String apkPath) {
        startService(new Intent(this, AutoInstallService.class));
        //自动安装需要保持屏幕常亮
        ScreenReceiver.Companion.turnScreenOn(1000 * 60 * 5);
        Intent localIntent = new Intent(Intent.ACTION_VIEW);
        localIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri;
        /**
         * Android7.0+禁止应用对外暴露file://uri，改为content://uri；具体参考FileProvider
         */
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(this, "com.swbyte.app.fileprovider", new File(apkPath));
            localIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(new File(apkPath));
        }
        localIntent.setDataAndType(uri, "application/vnd.android.package-archive"); //打开apk文件
        startActivity(localIntent);
    }

    public class DownloadReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 接收下载完成的广播
            long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            if (downloadId != mDownloadId) return;
            DownloadManager.Query query = new DownloadManager.Query().setFilterById(mDownloadId);
            Cursor cursor = mDownloadManager.query(query);
            if (cursor.moveToFirst()) {
                int status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
                switch (status) {
                    //下载暂停
                    case DownloadManager.STATUS_PAUSED:
                        break;
                    //下载延迟
                    case DownloadManager.STATUS_PENDING:
                        break;
                    //正在下载
                    case DownloadManager.STATUS_RUNNING:
                        break;
                    //下载完成
                    case DownloadManager.STATUS_SUCCESSFUL:
                        //下载完成
                        Log.e(TAG, "下载完成");
                        String apkUri = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI));
                        File file = new File(Uri.parse(apkUri).getPath());
                        apkPath = file.getAbsolutePath();
                        if (isRoot()) {
                            Log.e(TAG, "Root安装");
                            new InstalTask(apkPath).execute();
                        } else {
                            Log.e(TAG, "没有Root权限");
                            installAuto(apkPath);
                        }
                        break;
                    //下载失败
                    case DownloadManager.STATUS_FAILED:
                        Log.e(TAG, "下载失败");
                        break;
                }
            }
        }
    }

    public static boolean isRoot() {
        boolean bool = false;
        try {
            bool = new File("/system/bin/su").exists() || new File("/system/xbin/su").exists();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mDownloadReceiver);
        Log.e(TAG, "onDestroy:>>>>>>>");
    }

}
